﻿using System;
using BestHTTP;

namespace Networking.Runtime
{
    public class SimpleHttpRequest
    {
        private HTTPRequest _request;
        public Action<SimpleHttpRequest> OnRequestStateChanged;
        public bool IsDone => _request.State == HTTPRequestStates.Finished;
        public byte[] Data => _request.Response.Data;
        public HTTPRequestStates RequestState => _request.State;

        public SimpleHttpRequest(string url)
        {
            _request = new HTTPRequest(new Uri(url), RequestCallBack);
        }

        public void SendRequest()
        {
            _request.Send();
        }

        private void RequestCallBack(HTTPRequest req, HTTPResponse resp)
        {
            OnRequestStateChanged?.Invoke(this);
        }

        public void Dispose()
        {
            if (_request != null)
            {
                _request.Abort();
                _request.Clear();
                _request.Dispose();
            }

            OnRequestStateChanged = null;
            _request = null;
        }
    }
}